package com.scisoft.scan.control.shelves;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.CommonAdapter;
import com.scisoft.scan.control.CommonViewHolder;
import com.scisoft.scan.control.ScanHelper;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.shelves.ShelvesInfoBean;
import com.scisoft.scan.data.QueryPageBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.data.stock.StockInfoBean;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper;
import com.scisoft.scan.ws.WebServiceHelper_Shelves;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import static com.scisoft.scan.control.CommonAdapter.LOADING_END;
import static com.scisoft.scan.control.CommonAdapter.LOADING_MORE;
import static com.scisoft.scan.control.CommonAdapter.PULLUP_LOAD_MORE;

public class ShelvesPartQueryActivity  extends Activity {
    private ImageView iv_Back; //返回按钮
    private ImageView iv_query; //搜索按钮
    private ClearEditText et_bar;//搜索框
    //分页配置表
    private QueryPageBean pageBean = null;
    private int currentPage = 0;
    //分页显示控件
    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private StockAdapter stockAdapter;
    private LinearLayoutManager mLayoutManager;
    private int lastVisibleItem; //最后一个可见Item的位置，关键所在
    //数据
    private ShelvesInfoBean shelvesInfoBean;

    @Override
    @SuppressLint("ClickableViewAccessibility")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_stock);
        //初始化扫码
        init();
        //参数传递
        Intent intent = getIntent();
        shelvesInfoBean = (ShelvesInfoBean) intent.getSerializableExtra("data");
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        et_bar = findViewById(R.id.et_bar);
        //搜索框
        iv_query = findViewById(R.id.iv_query);
        iv_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QueryData(true);
            }
        });
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int fullWidth = displayMetrics.widthPixels;

        mRefreshLayout = findViewById(R.id.swipe_layout);
        mRefreshLayout.setEnabled(false);
        mRecyclerView = findViewById(R.id.lv_data);
        stockAdapter = new StockAdapter(ShelvesPartQueryActivity.this);
        stockAdapter.setItemLayout(R.layout.item_stock_noleftbutton, R.id.hsv, R.id.layout_show, R.id.layout_hide, fullWidth);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        stockAdapter.setOnItemClickListener(new StockAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                StockInfoBean stockInfoBean = stockAdapter.getItemData(position);
                if (stockInfoBean != null) {
                    CommonUtil.showPress(ShelvesPartQueryActivity.this);
                    PartToShelvesTask partToShelvesTask = new PartToShelvesTask(ShelvesPartQueryActivity.this, stockInfoBean);
                    partToShelvesTask.execute();
                }
            }
        });
        mRecyclerView.setAdapter(stockAdapter);
        //设置滑动监听
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //判断是否滑动到底
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == stockAdapter.getItemCount()) {
                    //滑动到底，需要改变状态为 上拉加载更多
                    stockAdapter.changeMoreStatus(LOADING_MORE);
                    QueryData(false);
                } else {
                    stockAdapter.changeMoreStatus(PULLUP_LOAD_MORE);
                }
            }

            //更新最后可见位置
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();

            }
        });
        QueryData(true);
    }

    //查询库存
    private void QueryData(boolean refresh) {
        CommonUtil.showPress(this);
        QueryTask queryTask = new QueryTask(ShelvesPartQueryActivity.this, refresh);
        queryTask.execute();
    }

    //配件上架服务
    class PartToShelvesTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private StockInfoBean stockInfoBean;

        PartToShelvesTask(Context context, StockInfoBean stockInfoBean) {
            super();
            mcontext = context;
            this.stockInfoBean = stockInfoBean;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //查询列表数据
                msg = WebServiceHelper_Shelves.SHELVES_06(shelvesInfoBean.shelvesId, stockInfoBean.partId,stockInfoBean.supplierCode);
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            if (msg.contains("成功")) {
                CommonUtil.hidePress();
                Toast.makeText(getApplicationContext(), "配件上架成功", Toast.LENGTH_LONG).show();
                finish();
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //配件上架服务
    class PartQueryAndToShelvesTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String barCode = "";

        PartQueryAndToShelvesTask(Context context, String barCode) {
            super();
            mcontext = context;
            this.barCode = barCode;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //查询列表数据
                BarCodeBean barCodeBean = WebServiceHelper.ParseBarCode(barCode);
                if (barCodeBean != null && barCodeBean.barType == BarCodeBean.BAR_PART && barCodeBean.partBean != null) {
                    if (!"".equals(barCodeBean.partBean.partId)) {
                        msg = WebServiceHelper_Shelves.SHELVES_06(shelvesInfoBean.shelvesId, barCodeBean.partBean.partId, barCodeBean.partBean.supplierCode);
                    }
                }

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            if (msg.contains("成功")) {
                CommonUtil.hidePress();
                Toast.makeText(getApplicationContext(), "配件上架成功", Toast.LENGTH_LONG).show();
                finish();
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //绑定数据
    private void BindData(Context context, List<StockInfoBean> newData, boolean refresh) {
        //清空
        stockAdapter.clearLeftMenuList();
        //数据
        if (!refresh) {
            if (newData.size() > 0) {
                stockAdapter.addMoreItem(newData);
            } else {
                stockAdapter.changeMoreStatus(LOADING_END);
            }
        } else {
            stockAdapter.clearAddItem(newData);
            if (newData.size() == 0) {
                stockAdapter.changeMoreStatus(LOADING_END);
            }
        }
    }

    //查询库存服务
    class QueryTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        boolean mrefresh = true;
        private List<StockInfoBean> newData = new ArrayList<>();

        QueryTask(Context context, boolean refresh) {
            super();
            mcontext = context;
            mrefresh = refresh;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //重新刷新
                if (mrefresh) {
                    pageBean = null;
                }
                //第一次程序时需要先查询分页信息
                if (pageBean == null) {
                    pageBean = WebServiceHelper_Shelves.SHELVES_11(et_bar.getUpperText().toString(), shelvesInfoBean.depotId);
                    currentPage = 0;
                }
                //翻页
                currentPage++;
                //判断是否全部显示，如果没有就查询下一页
                if (currentPage <= pageBean.pageCount) {
                    newData = WebServiceHelper_Shelves.SHELVES_05(et_bar.getUpperText().toString(), shelvesInfoBean.depotId, pageBean.pageSize, currentPage);
                }
                //超过最大页则返回
                if (currentPage > pageBean.pageCount) {
                    currentPage = pageBean.pageCount;
                }
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext, newData, mrefresh);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }


    //以下为扫码相关
    //初始化
    private void init(){
        //初始化Profile
        ScanHelper.CreateProfile(this);
        //设置广播消息的接收器
        registerReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        //IntentFilter intFilter = new IntentFilter(ScanManager.ACTION_SEND_SCAN_RESULT);
        //registerReceiver(mResultReceiver, intFilter);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScanHelper.ACTION_RESULT_NOTIFICATION);   // for notification result
        filter.addAction(ScanHelper.ACTION_RESULT);                // for error code result
        filter.addCategory(Intent.CATEGORY_DEFAULT);    // needed to get version info
        filter.addAction(ScanHelper.ACTION_SCAN_OUTPUT); // register to received broadcasts via DataWedge scanning
        registerReceiver(mResultReceiver, filter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ScanHelper.ACTION_SCAN_OUTPUT)) {
                // 处理扫码结果
                try {
                    String decodedData = intent.getStringExtra("com.symbol.datawedge.data_string");
                    CommonUtil.showPress(ShelvesPartQueryActivity.this);
                    PartQueryAndToShelvesTask partQueryAndToShelvesTask = new PartQueryAndToShelvesTask(ShelvesPartQueryActivity.this, decodedData);
                    partQueryAndToShelvesTask.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(ShelvesPartQueryActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };

    //适配器相关功能
    class StockAdapter extends CommonAdapter<StockInfoBean> {
        //构造函数
        public StockAdapter(Context context) {
            super(context);
        }

        @Override
        public void convert(CommonViewHolder holder, final StockInfoBean stockInfoBean, int position) {
            TextView tv_partNo = holder.getView(R.id.tv_partNo);
            TextView tv_partName = holder.getView(R.id.tv_partName);
            TextView tv_supplierName = holder.getView(R.id.tv_supplierName);
            TextView tv_ycj = holder.getView(R.id.tv_ycj);
            TextView tv_kcs = holder.getView(R.id.tv_kcs);
            TextView tv_kck = holder.getView(R.id.tv_kck);
            TextView tv_ck = holder.getView(R.id.tv_ck);
            TextView tv_hj = holder.getView(R.id.tv_hj);
            ImageView iv_img = holder.getView(R.id.iv_img);
            //获取相应索引的ItemBean对象
            StockInfoBean bean = mList.get(position);
            //设置控件的对应属性值
            tv_partNo.setText(bean.partNo);
            tv_partName.setText(bean.partName);
            tv_supplierName.setText(bean.supplierName);
            tv_kcs.setText(String.valueOf(bean.stockCount));
            tv_kck.setText(String.valueOf(bean.canUseCount));
            tv_ck.setText(bean.depotName);
            tv_hj.setText(bean.position);
            if (bean.imgUrl != null && !bean.imgUrl.equals("")) {
                Picasso.with(mContext).load(bean.imgUrl).into(iv_img);
            } else {
                iv_img.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_noimage));
            }
        }

    }
}
